<template>
  <div class="login-container">
    <van-nav-bar title="登录"></van-nav-bar>
<van-form @submit="onSubmit" ref="loginform">
  <van-field
    v-model="user.mobile"
    name="mobile"
    placeholder="请输入手机号"
    :rules="userFormRules.mobile"

  >
 <i slot="left-icon" class="icon icon-jiarongman"></i>
  </van-field>
  <van-field
    v-model="user.code"
    type="password"
    name="密码"
    placeholder="请输入验证码"
    :rules="userFormRules.code"
  >
 <i slot="left-icon" class="icon icon-jiarongman"></i>
  <template #button>
    <van-count-down :time="10000" format="ss 秒" v-if="istimeshow" @finish="istimeshow=false"/>
    <van-button native-type="button" class="send-code-btn" size="mini" round type="default" @click="onsendsms" v-else>
      发送验证码
    </van-button>
  </template>
  </van-field>
  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit">登录</van-button>
  </div>
</van-form>
  </div>
</template>

<script>
import { login, sendsms } from '@/api/user.js'
import { setToken, getToken } from '@/utils/storage.js'
export default {
  name: 'LoginPage',
  data () {
    return {
      user: {
        mobile: '',
        code: ''
      },
      userFormRules: {
        mobile: [{
          required: true,
          message: '手机号不能为空'
        }, {
          pattern: /^1[3|5|7|8]\d{9}$/,
          message: '手机号格式错误'
        }],
        code: [{
          required: true,
          message: '验证码不能为空'
        }, {
          pattern: /^\d{6}$/,
          message: '验证码格式错误'
        }]
      },
      istimeshow: false
    }
  },
  methods: {
    async onSubmit () {
      // 开始转圈圈
      this.$toast.loading({
        duration: 1000, // 持续时间，0表示持续展示不停止
        forbidClick: true, // 是否禁止背景点击
        message: '登录中...' // 提示消息
      })
      const user = this.user
      try {
        const res = await login(user)
        console.log(res)
        this.$toast.success('登录成功')
        setToken(res.data.data.token)
      } catch (err) {
        if (err.response.status === 401) {
          // console.log('登录失败', err)
          this.$toast.fail('登录失败，手机号或验证码错误')
        }
      }
      const a = getToken()
      if (a) {
        this.$router.push({
          path: '/home'
        })
      }
    },
    async  onsendsms () {
      try {
        await this.$refs.loginform.validate('mobile')
      } catch (err) {
        return console.log('验证失败', err)
      }
      this.istimeshow = true

      try {
        await sendsms(this.user.mobile)
        this.$toast('发送成功')
      } catch (err) {
        return console.log('验证失败', err)
      }
    }
  }
}
</script>
  <style scoped lang="less">
.van-nav-bar{
   background-color:#3196fa
}
</style>
